<?php

/**
 * @todo Spend comments
 * @todo Write unit test
 *
 */
class WidgetFormOrganizationalUnitCustomEnabledChoice extends sfWidgetFormDoctrineChoice
{
  
  const OPTION_ENABLED_IDS = 'enabled_ids';

  protected function configure ($options = array(), $attributes = array())
  {
    $this->addOption(self::OPTION_ENABLED_IDS, array());
    parent::configure($options, $attributes);
    $this->setOption('model', 'OrganizationalUnit');
  }

  public function getChoices ()
  {
    $choices = array();
    
    if (false !== $this->getOption('add_empty'))
    {
      $choices[''] = true === $this->getOption('add_empty') ? '' : $this->translate($this->getOption('add_empty'));
    }
    
    $treeObject = Doctrine_Core::getTable('OrganizationalUnit')->getTree();
    $entities = $treeObject->fetchTree();
    return $entities;
  }

  public function render ($name, $value = null, $attributes = array(), $errors = array())
  {
    if ($this->getOption('multiple'))
    {
      $attributes['multiple'] = 'multiple';
      
      if ('[]' != substr($name, - 2))
      {
        $name .= '[]';
      }
    }
    
    $choices = $this->getChoices();
    
    return $this->renderContentTag('select', "\n" . implode("\n", $this->getOptionsForSelect($value, $choices)) . "\n", 
        array_merge(array(
          'name' => $name), $attributes));
  }

  protected function getOptionsForSelect ($value, $choices)
  {
    $ids = $this->getOption('enabled_ids', array());
    
    $mainAttributes = $this->attributes;
    $this->attributes = array();
    
    if (! is_array($value))
    {
      $value = array(
        $value);
    }
    
    $value = array_map('strval', array_values($value));
    $value_set = array_flip($value);
    
    $options = array();
    foreach ($choices as $key => $option)
    {
      if (! is_null($option->getDeletedAt()))
      {
        continue;
      }
      $attributes = array(
        'value' => self::escapeOnce($option->getPrimaryKey()));
      if (isset($value_set[strval($option->getPrimaryKey())]))
      {
        $attributes['selected'] = 'selected';
      }
      if (! in_array($option->getId(), $ids))
      {
        $attributes['disabled'] = 'disabled';
      }
      
      $options[] = $this->renderContentTag('option', str_repeat('&nbsp;&nbsp;&nbsp;', $option->getLevel()) . self::escapeOnce($option), $attributes);
    }
    
    $this->attributes = $mainAttributes;
    
    return $options;
  }
}